<template>
  <!-- 上传文件组件 -->
  <el-upload
    ref="upload"
    class="upload-demo"
    :limit="1"
    :on-exceed="handleExceed"
    :auto-upload="false"
    :on-change="readFile"
    accept=".xlsx"
    :on-remove="removeFile"
  >
    <template #trigger>
      <el-button type="primary">选择表格</el-button>
    </template>
  </el-upload>

  <!-- 编辑按钮 -->
  <el-button type="primary" @click="editFile" :disabled="editFlag">{{
    text
  }}</el-button>

  <!-- 导出按钮 -->
  <el-button type="primary" @click="exportFile" :disabled="fileFlag">导出</el-button>
  <!-- 表格：展示上传的excel内容 -->
  <el-table :data="fileArr" style="width: 100%">
    <el-table-column v-for="item in titleArr" :prop="item" :label="item">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span style="margin-left: 10px" v-show="!fileFlag">{{
            scope.row[item]
          }}</span>
          <el-input
            v-model="scope.row[item]"
            :value="scope.row[item]"
            v-show="fileFlag"
          />
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import * as XLSX from "xlsx";

import { reactive, ref, shallowRef } from "vue";
import { genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { tr } from "element-plus/es/locales.mjs";

const upload = ref<UploadInstance>();

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

// 文件移出时的处理函数
const removeFile = () => {
  titleArr.value = [];
  fileArr.length = 0;
  editFlag.value = true;
};

// 存放表头
const titleArr = shallowRef([]);
// 存放所有表格数据
const fileArr = reactive([]);
const fileFlag = ref<boolean>(false);
const editFlag = ref<boolean>(true);

// 上传文件发生改变时的处理函数
const readFile: UploadProps["onChange"] = (files) => {
  // 清空之前的表格数据
  titleArr.value = [];
  fileArr.length = 0;

  console.log("文件内容：", files.raw);

  // 处理excel文件内容
  // 1.实例化读取文件的对象
  let reader = new FileReader();
  // 2.以二进制方式读取文件内容
  reader.readAsBinaryString(files.raw as any);
  // 3.正式处理
  reader.onload = (event) => {
    // 4.读取文件内容
    const fileString = event.target?.result;
    // 5.解析二进制格式的数据
    const workbook = XLSX.read(fileString, { type: "binary" });
    // 6.获取第一个sheet
    const workSheet = workbook.Sheets[workbook.SheetNames[0]];
    // 7.把表格内容转成json格式
    const result: any = XLSX.utils.sheet_to_json(workSheet);
    console.log("最终的数据：", result);

    // 处理数据：把数据做成如下格式
    // [
    //     {ID:123,name:张三，语文：12，数学：19}，
    //     {ID:123,name:张三，语文：12，数学：19}，
    //     {ID:123,name:张三，语文：12，数学：19}，
    //     {ID:123,name:张三，语文：12，数学：19}，
    // ]

    // 1.获取键名
    for (let i in result[0]) {
      titleArr.value.push(result[0][i] as never);
    }

    for (let i = 1; i < result.length; i++) {
      let j = 0; //表示titleArr的下标
      let studentObj: any = {}; //学生对象
      for (let x in result[i]) {
        studentObj[titleArr.value[j]] = result[i][x];
        j++;
      }
      fileArr.push(studentObj as never);
    }

    console.log(fileArr);

    editFlag.value = false;
  };
};

const text = ref("编辑");

// 编辑按钮的事件处理函数
const editFile = () => {
  if (text.value == "编辑") {
    text.value = "保存";
    fileFlag.value = !fileFlag.value;
  } else {
    text.value = "编辑";
    fileFlag.value = !fileFlag.value;
  }
};

// 导出文件
const exportFile=()=>{
    // 1.创建一个工作簿
    const workbook=XLSX.utils.book_new();
    // 2.导出的数据必须是一个二维数组，如下：
// var aoa = [
//     ['姓名', '性别', '年龄', '注册时间'],
//     ['张三', '男', 18, new Date()],
//     ['李四', '女', 22, new Date()]
// ];

    let Arr2=[];
    Arr2.push(titleArr.value);

    for(let i=0;i<fileArr.length;i++){
        let arr:Array<string>=[];
        for(let x in fileArr[i]){
            arr.push(fileArr[i][x]);
        }
        Arr2.push(arr);
    }

    // 3.创建一个工作表
    const worksheet=XLSX.utils.aoa_to_sheet(Arr2);
    // 4.将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook,worksheet,"Sheet1");
    // 5.生成一个Excel文件
    XLSX.writeFile(workbook,"data.xlsx");
}

</script>

<style scoped></style>
